<script setup>
import { ref, watch,onMounted} from 'vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { uploadImageOrfile, downloadFile, deleteFile } from '@/api/file'
import { saveCustomerApi,pageCustomerApi } from '@/api/customer'
import { queryAllApi } from "@/api/user"
import regionData from '@/assets/region.json';
onMounted(() => {
  onSubmit();
})
const regionOptions = ref(regionData);

// 搜索框
const formInline = ref({
  page: 1,
  size:10,
  name: '',
  source: '',
  startTime: '',
  endTime:'',
  date: []
})
watch(   
  () => formInline.value.date,
  (newValue) => {
    if (Array.isArray(newValue) && newValue.length === 2) {
      formInline.value.startTime = dayjs(newValue[0]).format('YYYY-MM-DD HH:mm:ss')
      formInline.value.endTime = dayjs(newValue[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
    } else {
      formInline.value.startTime = ''
      formInline.value.endTime = ''
    }
  }
)
const options = [
  {
    value: 1,
    label: "官网",
  }, {
    value: 2,
    label: "广告",
  }, {
    value: 3,
    label: "介绍",
  }
]
// 表格数据
const tableData = ref([]) // 空数组作为初始值
const tableRowClassName = ({ row }) => {
  if (!row.nextFollowTime) return '';

    const now = new Date();
    const followTime = new Date(row.nextFollowTime);
    const diffDays = (followTime - now) / (1000 * 60 * 60 * 24);

  if (diffDays < 0) {
      return 'row-red'; // 已超时
  } else if (diffDays <= 7) {
      return 'row-yellow'; // 剩 7 天以内
    }
    return '';
}
// 新增
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
//头像上传
const imageUrl = ref('')
const uploadRef = ref(null)
const UserList = ref([])
const titleName=ref()
const form = ref({
  id:'',     //主键id
  customerName: '', //公司名称
  profilePicture:'',//头像链接
  contactPerson: '',//联系人名称
  phone: '', //手机号
  email: '',//电子邮箱
  wechat: '',//微信号
  industry: '',//所属行业
  level: '',//客户级别
  source: '',//客户来源
  region: '',//所属地区
  regions:[],//所属地区
  address: '',//详细地址
  status: '',//状态
  followUserId:'',//跟进人id
  nextFollowTime: '',//下次跟进时间
  remark: '',//备注
  fileIds:'',//附件ids
})
const addUser=(title) => { 
  dialogFormVisible.value = true
  titleName.value = title
  imageUrl.value = ""
  searchUser();
}
//查看所有人员信息
const searchUser = async () => { 
  const list = await queryAllApi();
  UserList.value = list.data;
}
const handleClick = (row,title) => { 
  form.value = row

}
// 上传成功后的处理函数
const handleAvatarSuccess = (response, file) => {
  imageUrl.value = response.data;
    // 清除已上传文件，实现覆盖上传（关键代码）
  uploadRef.value.clearFiles()
};
//  上传图片
const customUpload = async ({ file, onSuccess, onError }) => {
  try {
    const result = await uploadImageOrfile(file);
    if (result.code === 200) {
      imageUrl.value = result.data;
      ElMessage.success("上传成功！");
      onSuccess(result); // 传入正确变量
    } else {
      ElMessage.error(result.message || "上传失败");
      onError(new Error(result.message || "上传失败"));
    }
  } catch (error) {
    ElMessage.error("上传异常：" + error.message);
    onError(error);
  }
};

// 上传前的校验函数
const beforeAvatarUpload = (rawFile) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
  if (!allowedTypes.includes(rawFile.type)) {
    ElMessage.error('头像必须是 jpg、png、gif 格式！')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不能超过 2MB！')
    return false
  }
  return true
}
//上传文件
const fileList = ref([])
const uploadFile = async ({ file, onSuccess, onError }) => {
  try {
    const result = await uploadImageOrfile(file)
    if (result.code === 200) {
      // 修改当前上传项的信息，不要 push 到 fileList
      file.url = result.data.url
      file.id = result.data.id

      ElMessage.success("上传成功")
      onSuccess(result)
    } else {
      ElMessage.error("上传失败")
      onError(new Error(result.msg))
    }
  } catch (error) {
    ElMessage.error("上传异常")
    onError(error)
  }
}
const ChangeFile = (uploadFile, uploadFiles) => {
  // 示例逻辑：始终只保留最后 3 个文件
  fileList.value = uploadFiles.slice(-3)
}
const previewFile = async (file) => {
  if (!file.raw.url) {
    ElMessage.warning('文件没有 URL，无法下载');
    return;
  }
  try {
    // 正确：这里直接拿到 Blob
    const blob = await downloadFile({ url: file.raw.url });

    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = file.name || 'download';

    document.body.appendChild(link);
    link.click();

    // 清理
    window.URL.revokeObjectURL(url);
    document.body.removeChild(link);

  } catch (error) {
    ElMessage.error('下载失败');
    console.error('下载错误详情：', error);
  }
};
//删除逻辑
const removeFile = async(file, fileListRaw) => {
    if (!file.raw.url) {
      ElMessage.warning('文件没有 URL，无法删除');
      return;
    }
    const result = await deleteFile({ id: file.raw.id,url:file.raw.url });
    if (result.code === 200) {
      ElMessage.success('删除成功');
    } else {
      ElMessage.error(result.msg);
  
  }
}
//保存用户
const saveUser = async() => {
  form.value.profilePicture=imageUrl.value  //头像链接
  const fileids = fileList.value.map(file => file.raw.id).join(',');
  form.value.fileIds = fileids;
  form.value.region = form.value.regions.join('/');
  const result = await saveCustomerApi(form.value);
  if (result.code === 200) {
    ElMessage.success('保存成功')
    dialogFormVisible.value = false
    form.value = {}
    imageUrl.value = ''
    fileList.value = []
    onSubmit();
  } else {
    ElMessage.error(result.msg)

  }
}
//分页
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const background = ref(false)
const disabled = ref(false)
const totalall = ref(0);
//清空搜索框
const onClear = () => {
  formInline.value.name = ''
  formInline.value.region = ''
  formInline.value.date = []
  formInline.value.startTime = ''
  formInline.value.endTime = '' 
}
const onSubmit = async () => {
  const result = await pageCustomerApi(formInline.value);
  tableData.value = result.data.records
  if (result.data.records != null || result.data.records.length > 0) {
    currentPage4.value = Number(result.data.current)
    pageSize4.value = Number(result.data.size)
    totalall.value = Number(result.data.total)   
  } else {
    disabled.value = true
  }
}
const handleSizeChange = (val) => {
  formInline.value.size = val
  onSubmit()
}
const handleCurrentChange = (val) => {
  formInline.value.page = val
  onSubmit()
}
</script>
<template>
  <!-- 头部 -->
<div class="container">
  <h1>客户管理</h1>
  <el-button type="primary" @click="addUser("新增客户")">+ 新增客户</el-button>
</div>
<!-- 搜索框 -->
 <div class="container"> 
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="客户姓名">
      <el-input v-model="formInline.name" placeholder="请输入姓名" clearable />
    </el-form-item>
    <el-form-item label="客户来源">
      <el-select
        v-model="formInline.source"
        filterable
        placeholder="请选择"
        style="width: 240px"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.label"
        />
      </el-select>
    </el-form-item>
       <el-form-item label="跟进时间">
       <el-date-picker
        v-model="formInline.date"
        type="daterange"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">查询</el-button>
      <el-button type="success" @click="onClear">清空</el-button>
    </el-form-item>
  </el-form>
 </div>
 <!-- table 数据展示 -->
 <div class="container">
    <el-table :data="tableData" border ref="singleTableRef" 
    :row-class-name="tableRowClassName"
    style="width: 100%" row-key="id">
    <el-table-column type="index" label="序号" width="90" align="center" />
    <el-table-column label="头像" width="100" align="center">
    <template #default="{ row }">
      <el-avatar :src="row.profilePicture" size="small" />
    </template>
  </el-table-column>
    <el-table-column prop="customerName" label="客户姓名/公司名称" width="150" show-overflow-tooltip align="center"/>
    <el-table-column prop="contactPerson" label="联系人名称" width="120" show-overflow-tooltip align="center" />
    <el-table-column prop="phone" label="电话号码" width="120" show-overflow-tooltip  align="center"/>
    <el-table-column prop="email" label="电子邮箱" width="120"  show-overflow-tooltip align="center"/>
    <el-table-column prop="industry" label="所属行业" width="120" show-overflow-tooltip  align="center"/>
    <el-table-column prop="source" label="客户来源" width="120" show-overflow-tooltip align="center"/>
    <el-table-column prop="level" label="客户级别" width="120" show-overflow-tooltip align="center"/>
    <el-table-column prop="region" label="所在区域" width="120" show-overflow-tooltip align="center"/>
    <el-table-column prop="followName" label="跟进人姓名" width="120" show-overflow-tooltip align="center"/>
    <el-table-column prop="nextFollowTime" label="下次跟进时间" show-overflow-tooltip width="120" align="center"/>
    <el-table-column fixed="right" label="操作" min-width="160">
      <template #default="scoped">
      <div class="mb-4" >
        <el-button   type="success"  size="small" @click="handleClick(scoped.row,"修改")>
          查看
        </el-button>
        <el-button  type="warning" size="small">修改</el-button>
      </div>
      </template>
    </el-table-column>
  </el-table>
  </div>
<!-- 分页 -->
<div class="container">
    <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="currentPage4"  
      v-model:page-size="pageSize4"
      :page-sizes="[10, 20, 30, 40]"
      size="default"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalall"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</div>
  <!-- 新增弹窗 -->
  <el-dialog v-model="dialogFormVisible" :title="titleName" width="1000">
  <el-form :model="form">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="公司名称" :label-width="formLabelWidth">
          <el-input v-model="form.customerName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="电子邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.email" autocomplete="off" />
        </el-form-item>
        <el-form-item label="微信号" :label-width="formLabelWidth">
          <el-input v-model="form.wechat" autocomplete="off" />
        </el-form-item>
        <el-form-item label="跟进人" :label-width="formLabelWidth">
          <el-select v-model="form.followUserId" placeholder="请选择">
            <el-option
              v-for="user in UserList"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            >
              <div style="display: flex; justify-content: space-between;">
              <span>{{ user.name }}</span>
              <span style="color: #999; font-size: 12px;">{{ user.deptName }}</span>
            </div>
          </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下次跟进时间" :label-width="formLabelWidth">
          <div class="block">
            <el-date-picker
              v-model="form.nextFollowTime"
              type="date"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择时间"
              :default-value="new Date()"
            />
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="联系人" :label-width="formLabelWidth">
          <el-input v-model="form.contactPerson" autocomplete="off" />
        </el-form-item>
        <el-form-item label="客户级别" :label-width="formLabelWidth">
          <el-select v-model="form.level" placeholder="请选择">
            <el-option label="A" value="A" />
            <el-option label="B" value="B" />
            <el-option label="C" value="C" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户来源" :label-width="formLabelWidth">
          <el-select v-model="form.source" placeholder="请选择">
            <el-option label="官网" value="官网" />
            <el-option label="广告" value="广告" />
            <el-option label="介绍" value="介绍" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option label="潜在客户" value="0" />
            <el-option label="正式客户" value="1" />
            <el-option label="流失" value="2" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="电话号码" :label-width="formLabelWidth">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="所属行业" :label-width="formLabelWidth">
          <el-input v-model="form.industry" />
        </el-form-item>
        <el-form-item label="所在地区" :label-width="formLabelWidth">
          <el-cascader
              v-model="form.regions"
              :options="regionOptions"
              placeholder="请选择省 / 市 / 区"
              :props="{
                value: 'name',
                label: 'name',
                children: 'children'
              }"
              clearable
            />
        </el-form-item>
        <el-form-item label="详细地址" :label-width="formLabelWidth">
          <el-input v-model="form.address" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="头像" :label-width="formLabelWidth">
        <el-upload
          class="avatar-uploader"
          ref="uploadRef"
          action=""
          :http-request="customUpload"
          :limit="1"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
    </el-form-item>
    <el-form-item label="附件" :label-width="formLabelWidth">
      <el-upload
        v-model:file-list="fileList"
        class="upload-demo"
        :http-request="uploadFile"
        :on-change="ChangeFile"
        :on-preview="previewFile"
        :on-remove="removeFile"
      >
        <el-button type="primary">上传文件</el-button>
        <template #tip>
          <div class="el-upload__tip">
          </div>
        </template>
      </el-upload>
    </el-form-item>
    <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.remark" autocomplete="off" />
    </el-form-item>
  </el-form>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="saveUser">提交</el-button>
    </div>
  </template>
</el-dialog>
</template>

<style scoped>
/* 禁用 hover 效果，确保样式不被覆盖 */
::v-deep(.el-table__body tr:hover > td),
::v-deep(.el-table__body .hover-row td) {
  background-color: transparent !important;
}
.container {
  margin: 15px 0;
}

/* ::v-deep 用于穿透 scoped */
::v-deep(.row-yellow) {
  background-color: #ffd700 !important;
  color: #000 !important;
  font-weight: bold;
  border-left: 4px solid #ffa500;
}

::v-deep(.row-red) {
  background-color: #ff4c4c !important;
  color: #000 !important;
  font-weight: bold;
  border-left: 4px solid #cc0000;
}
::v-deep(.row-yellow:hover) {
  background-color: #FFD700 !important;
}

/* 图片上传样式 */
/* 图片上传样式 */
::v-deep(.avatar-uploader .avatar) {
  width: 178px;
  height: 178px;
  display: block;
}

::v-deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

::v-deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

::v-deep(.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
